package com.example.mobileshop.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.example.mobileshop.models.Shop;
import com.example.mobileshop.utils.Const;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class  ShopController{
	private String URL_JSON_SHOP_ALL = Const.URL_HOST_WS + "/api/v1/shops";
	private String URL_JSON_SHOP_A_PAGE = Const.URL_HOST_WS + "/api/v1/shops/getshops";
	private HttpClient client = new DefaultHttpClient();
	private List<Shop> listShop = new ArrayList<Shop>();		
	private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create(); 
	
	public List<Shop> getAllShops(){						
		HttpGet postMethod = new HttpGet(URL_JSON_SHOP_ALL);		
		try {
		    HttpResponse response = client.execute(postMethod);
		    String responseData = EntityUtils.toString(response.getEntity(), "utf-8");
		    Shop[] arrayShops = gson.fromJson(responseData, Shop[].class);
		    listShop = Arrays.asList(arrayShops);
		} catch(final Exception e) {
		    // handle exception here
		}
		return listShop;
	}
	
	public List<Shop> getShopsForAPage(int pageIdx){						
		HttpGet postMethod = new HttpGet(URL_JSON_SHOP_A_PAGE + "/" + pageIdx + "/" + Const.NUM_OF_SHOPS_ON_PAGE);		
		try {
		    HttpResponse response = client.execute(postMethod);
		    String responseData = EntityUtils.toString(response.getEntity(), "utf-8");
		    Shop[] arrayShops = gson.fromJson(responseData, Shop[].class);
		    listShop = Arrays.asList(arrayShops);
		} catch(Exception e) {
		    // handle exception here
			e.printStackTrace();
		}
		return listShop;
	}
}